package repo

import (
	"easy-note/models"
	"fmt"
	"gorm.io/gorm"
)

var DB *gorm.DB

type NoteRepo struct{}

func (noteRepo *NoteRepo) InsertNote(note *models.NoteInfo) (bool, error) {
	db := DB.Create(note)
	err := db.Error
	if err != nil {
		return false, err
	}
	return db.RowsAffected > 0, nil
}

func (noteRepo *NoteRepo) DeleteNote(id, userId int) (bool, error) {
	db := DB.Delete(&models.NoteInfo{UserId: userId}, &id)
	err := db.Error
	if err != nil {
		return false, err
	}
	return db.RowsAffected > 0, nil
}

func (noteRepo *NoteRepo) UpdateNote(id, userId int, name, note string) (bool, error) {
	db := DB.Model(
		&models.NoteInfo{
			UserId: userId,
			BaseModel: models.BaseModel{
				Id: id,
			}}).Updates(&models.NoteInfo{
		Name: name,
		Note: note,
	})

	err := db.Error
	if err != nil {
		return false, err
	}
	return db.RowsAffected > 0, nil
}

func (noteRepo *NoteRepo) GetNoteById(id, userId int) (*models.NoteInfo, error) {
	var note *models.NoteInfo
	err := DB.First(&note, &models.NoteInfo{
		UserId: userId,
		BaseModel: models.BaseModel{
			Id: id,
		}}).Error
	if err != nil {
		return nil, err
	}
	return note, nil
}

func (noteRepo *NoteRepo) ListNote(page, size, userId int, total *int64) ([]*models.NoteInfo, error) {
	var notes []*models.NoteInfo
	db := DB.Model(&models.NoteInfo{UserId: userId})
	err := db.Count(total).Error
	if err != nil {
		return nil, err
	}
	if *total == 0 {
		return nil, fmt.Errorf("找不到数据")
	}
	err = db.Offset((page - 1) * size).Limit(size).Find(&notes).Error
	if err != nil {
		return nil, err
	}
	return notes, nil
}
